<template>
  <div class="app-container">
    <!-- 菜单头部 -->
    <header v-show="!isAppCollapsed" class="app-header">
      <div class="header-content">
        <!-- 左侧LOGO和导航 -->
        <div class="header-left">
          <div class="logo-container">
            <div class="logo" style="width: 150px">{{ systemName }}</div>
          </div>

          <!-- 导航菜单 -->
          <nav class="nav-menu">
            <ul class="menu-primary">
              <li
                  v-for="(item, index) in menuItems"
                  :key="item.id"
                  :class="{ 'active': activeTopMenuId === item.id || activeSubMenuParentId === item.id }"
                  class="menu-item"
                  @mouseenter="setActiveIndex(index)"
                  @mouseleave="clearActiveIndex"
              >
                <router-link
                    :to="item.router"
                    class="menu-link"
                    @click="handleTopMenuClick(item)"
                >
                  <span class="menu-text">{{ item.title }}</span>
                  <span v-if="item.children && item.children?.length>0" class="menu-arrow">
                    <svg fill="none" height="16" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                         stroke-width="2" viewBox="0 0 24 24" width="16" xmlns="http://www.w3.org/2000/svg">
                      <polyline points="6 9 12 15 18 9"></polyline>
                    </svg>
                  </span>
                </router-link>

                <transition name="slide-fade">
                  <ul
                      v-if="item.children && item.children?.length>0"
                      :class="{ 'is-active': activeIndex === index }"
                      class="menu-secondary"
                      @mouseenter="setActiveIndex(index)"
                  >
                    <li
                        v-for="child in item.children"
                        :key="child.id"
                        :class="{ 'active': activeSubMenuId === child.id }"
                        class="menu-secondary-item"
                    >
                      <router-link
                          :to="child.router"
                          class="menu-secondary-link"
                          @click="handleSubMenuClick(child, item)"
                      >
                        {{ child.title }}
                      </router-link>
                    </li>
                  </ul>
                </transition>
              </li>
            </ul>
          </nav>
        </div>

        <!-- 右侧用户信息 -->
        <div class="right-info">
          <div class="clock-info">
            <div class="clock">
              <p>{{ displayTime }}</p>
            </div>
          </div>

          <div class="user-info">
            <span class="username">{{ userInfo.nickname }}</span>
            <div class="avatar">
              <img alt="用户头像" src="@/asserts/girl.jpg"/>
            </div>
            <div class="user-dropdown">
              <a href="#" @click="handleUserInfo">个人中心</a>
              <a href="#" @click="handleSysConfig">设置</a>
              <a href="#" @click="handleLogout">退出登录</a>
            </div>
          </div>
        </div>
      </div>
    </header>


    <!-- 右侧折叠浮标 -->
    <div
        :class="{ 'collapsed': isAppCollapsed }"
        class="collapse-float"
        @click="toggleCollapse"
    >
      <span class="tooltip">{{ isAppCollapsed ? '展开' : '折叠' }}</span>
    </div>

    <!-- 页面内容 -->
    <main :style="{ height: pageHeight }" class="app-content">
      <RouterView></RouterView>
    </main>
  </div>
</template>

<script lang="ts" setup>
import {computed, onBeforeUnmount, onMounted, onUnmounted, ref, watch} from 'vue';
import {logout} from "@/api/system/sysUser";
import {getUserInfo, removeUserInfo} from "@/utils/system";
import {useRoute} from "vue-router";
import {message, notificationBox} from "@/utils/ElmessasgeUtils";
import type {MenuItem} from "@/type/common/MenuRouter";
import {storeToRefs} from "pinia";
import router, {filterMenus} from "@/router";
import {formatCurrentTime} from "@/utils/dateUtils";
import type {UserInfo} from "@/type/systemConfig/sysUserInfo";
import {isAppCollapsed, MainMenuItems, useMainStore} from "@/main";
import {useWebSocketStore} from "@/stores/webSocketStore";
import {WEBSOCKET_MESSAGE_TYPE} from "@/enum/admin/WebSocketDataTypeEnum";

const mainStore = useMainStore()
const {systemName} = storeToRefs(mainStore)
const route = useRoute();

const pageHeight = computed(() => {
  return `calc(100vh - ${isAppCollapsed.value ? '0vh' : currentPath.value.length > 0 ? '8vh' : '5vh'})`;
});

const currentTime = ref('');
currentTime.value = formatCurrentTime();


const activeIndex = ref<number | null>(null);
const activeTopMenuId = ref<string | null>(null);
const activeSubMenuId = ref<string | null>(null);
const activeSubMenuParentId = ref<string | null>(null);

// 过滤出要显示的菜单
let menuItems = filterMenus(MainMenuItems.value, [1, 2]);

// 当前路径数据
interface PathItem {
  title: string;
}

const currentPath = ref<PathItem[]>([]);

// 更新当前路径显示和激活菜单
const updateActiveMenu = () => {
  if (route.path === '/login') {
    message("登录页")
  }

  const path = route.path;
  currentPath.value = [];
  activeTopMenuId.value = null;
  activeSubMenuId.value = null;
  activeSubMenuParentId.value = null;

  // 查找匹配的菜单项
  for (const menuItem of menuItems) {
    if (path.startsWith(menuItem.router)) {
      // 一级菜单匹配
      activeTopMenuId.value = menuItem.id;
      currentPath.value.push({
        title: menuItem.title
      });

      // 查找匹配的二级菜单
      if (menuItem.children) {
        for (const childItem of menuItem.children) {
          if (path === childItem.router || path.startsWith(childItem.router + '/')) {
            activeSubMenuId.value = childItem.id;
            activeSubMenuParentId.value = menuItem.id;
            currentPath.value.push({
              title: childItem.title
            });
            break;
          }
        }
      }
      break;
    }
  }
};

// 监听路由变化
watch(() => route.path, updateActiveMenu, {immediate: true});


const userInfo = ref<UserInfo>({});

const toggleCollapse = () => {
  isAppCollapsed.value = !isAppCollapsed.value;
};

const setActiveIndex = (index: number) => {
  activeIndex.value = index;
};

const clearActiveIndex = () => {
  activeIndex.value = null;
};

const handleTopMenuClick = (menuItem: MenuItem) => {
  activeTopMenuId.value = menuItem.id;
  activeSubMenuId.value = null;
  activeSubMenuParentId.value = null;
};

const handleSubMenuClick = (childItem: MenuItem, parentItem: MenuItem) => {
  activeSubMenuId.value = childItem.id;
  activeSubMenuParentId.value = parentItem.id;
};

function handleLogout() {
  logout().then((res) => {
    if (res.data.code === 200) {
      removeUserInfo()
      router.replace('/login')
    } else {
      message('退出失败', 'error')
    }
  })
}

function handleUserInfo() {
  router.push({name: 'userInfo'})
}

function handleSysConfig() {
  console.log('系统设置')
}

const localTime = ref(new Date())
// 更新本地时间
const updateLocalTime = (): void => {
  localTime.value = new Date()
}

// 每秒更新本地时间
const timer = setInterval(updateLocalTime, 1000)

// 计算显示时间（根据服务器时间校准）
const displayTime = computed(() => {
  return localTime.value.toLocaleString('zh-CN')

})


// 在应用启动时初始化 WebSocket
const websocketStore = useWebSocketStore()

websocketStore.onMessage(WEBSOCKET_MESSAGE_TYPE.SYSTEM_TIME_SYNC, handleSyncTime)

function handleSyncTime(payload: any) {
  console.log(payload.data.formatTime)
}



onMounted(async () => {

  userInfo.value = getUserInfo()
  if (!userInfo.value.nickname) {
    setTimeout(() => {
      router.push('/login'), 2000
    })
  } else {
    await websocketStore.connect()
  }
})

onBeforeUnmount(async () => {
  await websocketStore.disconnect()
  clearInterval(timer)
})
</script>

<style scoped>
/* 基础样式 */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden;
  font-family: '微软雅黑', sans-serif;
}

.app-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  position: relative;
}

.app-header {
  height: 5vh;
  background: #2c3e50;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 2px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.header-left {
  display: flex;
  align-items: center;
}

/* 用户信息区域 */
.right-info {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
}


/* 导航菜单样式 */
.nav-menu {
  display: flex;
  height: 100%;
}

.menu-primary {
  display: flex;
  list-style: none;
  margin: 0;
  padding: 0;
  height: 100%;
}

.menu-item {
  position: relative;
  display: flex;
  align-items: center;
  height: 100%;
  padding: 0 15px;
}

.menu-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.menu-item.active {
  background-color: rgba(255, 255, 255, 0.2);
}

.menu-link {
  display: flex;
  align-items: center;
  text-decoration: none;
  color: white;
  font-weight: 500;
  height: 100%;
  padding: 0 8px;
  transition: all 0.2s;
}

.menu-text {
  margin-right: 5px;
}

.menu-arrow {
  display: flex;
  align-items: center;
  transition: transform 0.2s;
}

.menu-item:hover .menu-arrow {
  transform: rotate(180deg);
}

/* 二级菜单样式 */
.menu-secondary {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  min-width: 180px;
  background: white;
  list-style: none;
  padding: 6px 0;
  margin: 0;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  opacity: 0;
  visibility: hidden;
  transform: translateY(5px);
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
  z-index: 100;
}

.menu-secondary.is-active {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.menu-secondary-item {
  padding: 0 8px;
}

.menu-secondary-item.active {
  background-color: #f7fafc;
}

.menu-secondary-link {
  display: block;
  padding: 8px 16px;
  text-decoration: none;
  color: #4a5568;
  border-radius: 6px;
  transition: all 0.2s ease;
  font-size: 14px;
}

.menu-secondary-link:hover,
.menu-secondary-item.active .menu-secondary-link {
  background-color: #ebf8ff;
  color: #3182ce;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.username {
  margin-right: 10px;
  font-size: 0.9rem;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid rgba(255, 255, 255, 0.3);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-dropdown {
  position: absolute;
  top: 100%;
  right: 0;
  background: white;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  min-width: 160px;
  z-index: 1000;
  opacity: 0;
  visibility: hidden;
  transform: translateY(10px);
  transition: all 0.2s ease;
}

.user-info:hover .user-dropdown {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.user-dropdown a {
  display: block;
  padding: 8px 16px;
  color: #333;
  text-decoration: none;
  transition: background-color 0.2s;
}

.user-dropdown a:hover {
  background-color: #f5f5f5;
}

/* 时钟样式 */
.clock-info {
  margin-right: 20px;
  display: flex;
  align-items: center;
  position: relative;
}

/* 右侧折叠浮标样式 */
.collapse-float {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 10px;
  height: 60px;
  background: #2c3e50;
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 100;
  transition: all 0.3s ease;
  box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.collapse-float:hover {
  width: 60px;
  background: #34495e;
}

.collapse-float:hover .tooltip {
  opacity: 1;
}

.collapse-float .icon {
  color: white;
  font-weight: bold;
  font-size: 14px;
  user-select: none;
  transition: transform 0.3s ease;
}

.collapse-float .tooltip {
  position: absolute;
  color: white;
  font-size: 12px;
  white-space: nowrap;
  opacity: 0;
  transition: opacity 0.2s ease;
  left: 8px;
}

.collapse-float.collapsed .icon {
  transform: rotate(180deg);
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo {
  width: 150px;
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

/* 页面内容样式 */
.app-content {
  flex: 1;
  overflow: auto;
  padding: 0px;
  background: #f5f5f5;
}

/* 动画效果 */
.slide-fade-enter-active {
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.slide-fade-leave-active {
  transition: all 0.2s cubic-bezier(0.4, 0, 1, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(10px);
}
</style>